package com.sec.etech.ism.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sec.etech.ism.factory.IsmFactory;
import com.sec.etech.ism.mapper.IsmTaskJobMapper;
import com.sec.etech.ism.model.IsmTaskJob;
import lombok.extern.slf4j.Slf4j;
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class IsmTaskJobService extends ServiceImpl<IsmTaskJobMapper, IsmTaskJob> {

    @Autowired
    IsmService ismService;

    // 每2分钟检查一次
    @Scheduled(cron = "20 */2 * * * ? ")
    @SchedulerLock(name = "executeTaskJob", lockAtMostFor="2M", lockAtLeastFor="2M")
    public void executeTaskJob(){
        List<IsmTaskJob> jobList = this.baseMapper.selectList(Wrappers.<IsmTaskJob>lambdaQuery()
                .eq(IsmTaskJob::getStatus, 0));
        if(jobList!=null && jobList.size()>0){
            for(IsmTaskJob job:jobList){
                try {
                    IsmMethodService ismMethodService = IsmFactory.getIsmMethodService(job.getServerCode());
                    JSONObject result = ismMethodService.call(job.getSysCode(), job.getServerCode(),
                            JSONObject.parseObject(job.getBusinessParams()));
                    if ("success".equals(result.getString("flag"))) {
                        baseMapper.deleteById(job.getJobId());
                    } else {
                        job.setStatus(3);
                        baseMapper.updateById(job);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    job.setStatus(3);
                    baseMapper.updateById(job);
                }
            }
        }
    }

    // 每周六凌晨10分
    @Scheduled(cron = "0 10 0 ? * 7")
    @SchedulerLock(name = "executeSendPlanWarehouseDate", lockAtMostFor="2M", lockAtLeastFor="2M")
    public void executeSendPlanWarehouseDate(){
        JSONObject resObj = ismService.call3rdService("pcs", "sendPlanWarehouseDate", null);
        log.info("executeSendPlanWarehouseDate执行时间{}，执行结果{}。", new Date(), resObj);
    }
}
